import React, { PureComponent, Fragment } from 'react';
import { Button, Input, Popconfirm, Divider, InputNumber, Select, message } from 'antd';
import { TableC, PrimaryC } from '../../../../comps';
import uuid from 'es6-uuid';
import { generateSelect, showValue, generateSelectForObj, showValueForObj } from '../../../PortfolioManagement/utils';

const checkMap = {
  account: ['type-账户类型', 'account-账户', 'name-账户名称', 'bank-开户行', 'institution-机构', 'seat-席位'],
  trusteeship: ['type-账户类型', 'account-账户', 'name-账户名称', 'bank-开户行', 'institution-机构', 'seat-席位'],
  capital: ['type-账户类型', 'account-账户', 'name-账户名称', 'bank-开户行', 'institution-机构', 'seat-席位'],
  transaction: ['modes-交易模式', 'place-交易场所'],
  cost: ['type-费用类型', 'rate-提取比例'],
  fund: ['aggregateAmount-累计份额', 'aggregateMoney-累计投入金额'],
};

export default class ExtensionList extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      data: props.value,
      loading: false,
    };
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    if ('value' in nextProps) {
      this.setState({
        data: nextProps.value,
      });
    }
  }

  getRowByKey(key, newData) {
    return (newData || this.state.data).filter((item) => item.key === key)[0];
  }
  index = 0;
  cacheOriginData = {};
  toggleEditable = (e, key) => {
    e.preventDefault();
    const newData = this.state.data.map((item) => ({ ...item }));
    const target = this.getRowByKey(key, newData);

    if (target) {
      // 进入编辑状态时保存原始数据
      if (!target.editable) {
        this.cacheOriginData[key] = { ...target };
      }
      target.editable = !target.editable;
      this.setState({ data: newData });
      setTimeout(() => {
        this.props.onChange(this.state.data);
      }, 10);
    }
  };

  remove(key) {
    const newData = this.state.data.filter((item) => item.key !== key);
    this.setState({ data: newData });
    this.props.onChange(newData);
  }
  newMember = () => {
    const { type } = this.props;

    let statedata = this.state.data ? this.state.data : [];
    const newData = statedata.map((item) => ({ ...item }));
    const account = {
      id: uuid(32),
      key: uuid(32),
      editable: true,
      isNew: true,
    };
    const cost = {
      id: uuid(32),
      key: uuid(32),
      type: undefined,
      extractFrequency: '',
      extractStandard: '',
      remark: '',
      editable: true,
      isNew: true,
    };
    const fund = {
      id: uuid(32),
      key: uuid(32),
      editable: true,
      isNew: true,
    };
    const tran = {
      id: uuid(32),
      key: uuid(32),
      editable: true,
      isNew: true,
    };

    if (type === 'account') newData.push(account);
    if (type === 'cost') newData.push(cost);
    if (type === 'fund') newData.push(fund);
    if (type === 'trusteeship') newData.push(account);
    if (type === 'capital') newData.push(account);
    if (type === 'transaction') {
      if (newData.length > 0) {
        message.warning('交易信息最多增加一条！');
      } else {
        newData.push(tran);
      }
    }

    this.index += 1;
    this.setState({ data: newData });
    this.props.onChange(newData);
  };

  handleKeyPress(e, key) {
    if (e.key === 'Enter') {
      this.saveRow(e, key);
    }
  }
  handleFieldChange(e, fieldName, key) {
    if (!e) return;
    const newData = this.state.data.map((item) => ({ ...item }));
    const target = this.getRowByKey(key, newData);
    if (target) {
      if (fieldName == 'place') {
        let flag = e.some((item) => {
          return item == 'ALL';
        });
        if (flag) {
          target[fieldName] = ['ALL'];
        } else {
          target[fieldName] = e.target ? e.target.value : e;
        }
      } else {
        target[fieldName] = e.target ? e.target.value : e;
      }
      this.setState({ data: newData });
    }
  }
  handleInstitutionChange(e, fieldName, key) {
    const newData = this.state.data.map((item) => ({ ...item }));
    const target = this.getRowByKey(key, newData);
    if (target) {
      target[fieldName] = e;
      // 如果是上交所和深交所
      if (e === '2' || e === '3') {
        target.seat = '';
      } else {
        target.seat = '\\';
      }
      this.setState({ data: newData });
    }
  }
  saveRow = (e, key) => {
    const { type } = this.props;
    e.persist();
    if (this.clickedCancel) {
      this.clickedCancel = false;
      return;
    }
    const target = this.getRowByKey(key) || {};
    // 校验必填
    let flag = true;
    checkMap[type].forEach((element) => {
      const arr = element.split('-');
      if (!target[arr[0]]) {
        flag = false;
        message.error(`请填写${arr[1]}`);
      }
    });
    if (flag) {
      delete target.isNew;
      this.toggleEditable(e, key);
      setTimeout(() => {
        this.props.onChange(this.state.data);
      }, 1);
    }
  };

  // 生成列
  generateColumns = () => {
    const { type, dictMap, editabled, AccountConfigAllowedMarket, TransactionMode } = this.props;
    const costColumns = [
      {
        title: '费用类型',
        dataIndex: 'type',
        key: 'type',
        width: '20%',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Select style={{ width: '100%' }} onChange={(e) => this.handleFieldChange(e, 'type', record.key)} value={text} placeholder='请选择'>
                {generateSelect('MAAT_PRODUCT_COST_TYPE', dictMap)}
              </Select>
            );
          }
          return showValue('MAAT_PRODUCT_COST_TYPE', dictMap, text);
        },
      },
      {
        title: '费率(%)',
        dataIndex: 'rate',
        key: 'rate',
        render: (text, record) => {
          if (record.editable) {
            return (
              <InputNumber
                style={{ width: '100%' }}
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'rate', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                precision={4}
                min={0}
                max={100}
                formatter={(value) => `${value}%`}
                parser={(value) => value.replace('%', '')}
              />
            );
          }
          return text ? `${text}%` : text === 0 ? '0%' : '-';
        },
      },

      {
        title: '提取频率',
        dataIndex: 'extractFrequency',
        key: 'extractFrequency',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'extractFrequency', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                placeholder='提取频率'
              />
            );
          }
          return text;
        },
      },
      {
        title: '提取基准',
        dataIndex: 'extractStandard',
        key: 'extractStandard',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'extractStandard', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                placeholder='提取基准'
              />
            );
          }
          return text;
        },
      },
      {
        title: '备注',
        dataIndex: 'remark',
        key: 'remark',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'remark', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                placeholder='remark'
              />
            );
          }
          return text;
        },
      },
    ];
    const accountColumns = [
      {
        title: '账户类型',
        dataIndex: 'type',
        key: 'type',
        width: '12%',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Select style={{ width: '100%' }} onChange={(e) => this.handleFieldChange(e, 'type', record.key)} value={text} placeholder='请选择'>
                {generateSelect('MAAT_PRODUCT_ACCOUNT_TYPE', dictMap)}
              </Select>
            );
          }
          return showValue('MAAT_PRODUCT_ACCOUNT_TYPE', dictMap, text);
        },
      },
      {
        title: '账户',
        dataIndex: 'account',
        key: 'account',
        width: '16%',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'account', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                placeholder='账户'
              />
            );
          }
          return text;
        },
      },
      {
        title: '账户名称',
        dataIndex: 'name',
        key: 'name',
        width: '16%',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'name', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                placeholder='账户名称'
              />
            );
          }
          return text;
        },
      },
      {
        title: '开户行',
        dataIndex: 'bank',
        key: 'bank',
        width: '16%',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'bank', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                placeholder='开户行'
              />
            );
          }
          return text;
        },
      },
      {
        title: '机构',
        dataIndex: 'institution',
        key: 'institution',
        width: '12%',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Select style={{ width: '100%' }} onChange={(e) => this.handleInstitutionChange(e, 'institution', record.key)} value={text} placeholder='请选择'>
                {generateSelect('MAAT_PRODUCT_ACCOUNT_INSTITUTION', dictMap)}
              </Select>
            );
          }
          return showValue('MAAT_PRODUCT_ACCOUNT_INSTITUTION', dictMap, text);
        },
      },
      {
        title: '席位',
        dataIndex: 'seat',
        key: 'seat',
        width: '16%',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                disabled={record.institution !== '2' && record.institution !== '3'}
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'seat', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                placeholder='席位'
              />
            );
          }
          return text;
        },
      },
    ];
    const trusteeshipColumns = [
      {
        title: '账户类型',
        dataIndex: 'type',
        key: 'type',
        width: '12%',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Select style={{ width: '100%' }} onChange={(e) => this.handleFieldChange(e, 'type', record.key)} value={'0'} disabled={true} placeholder='请选择'>
                {generateSelect('MAAT_PRODUCT_ACCOUNT_TYPE', dictMap)}
              </Select>
            );
          }
          return showValue('MAAT_PRODUCT_ACCOUNT_TYPE', dictMap, text);
        },
      },
      {
        title: '账户',
        dataIndex: 'account',
        key: 'account',
        width: '16%',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'account', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                placeholder='账户'
              />
            );
          }
          return text;
        },
      },
      {
        title: '账户名称',
        dataIndex: 'name',
        key: 'name',
        width: '16%',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'name', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                placeholder='账户名称'
              />
            );
          }
          return text;
        },
      },
      {
        title: '开户行',
        dataIndex: 'bank',
        key: 'bank',
        width: '16%',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'bank', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                placeholder='开户行'
              />
            );
          }
          return text;
        },
      },
      {
        title: '机构',
        dataIndex: 'institution',
        key: 'institution',
        width: '12%',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Select style={{ width: '100%' }} onChange={(e) => this.handleInstitutionChange(e, 'institution', record.key)} value={text} placeholder='请选择'>
                {generateSelect('MAAT_PRODUCT_ACCOUNT_INSTITUTION', dictMap)}
              </Select>
            );
          }
          return showValue('MAAT_PRODUCT_ACCOUNT_INSTITUTION', dictMap, text);
        },
      },
      {
        title: '席位',
        dataIndex: 'seat',
        key: 'seat',
        width: '16%',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                disabled={record.institution !== '2' && record.institution !== '3'}
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'seat', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                placeholder='席位'
              />
            );
          }
          return text;
        },
      },
    ];
    const capitalColumns = [
      {
        title: '账户类型',
        dataIndex: 'type',
        key: 'type',
        width: '12%',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Select style={{ width: '100%' }} onChange={(e) => this.handleFieldChange(e, 'type', record.key)} value={'1'} placeholder='请选择' disabled={true}>
                {generateSelect('MAAT_PRODUCT_ACCOUNT_TYPE', dictMap)}
              </Select>
            );
          }
          return showValue('MAAT_PRODUCT_ACCOUNT_TYPE', dictMap, text);
        },
      },
      {
        title: '账户',
        dataIndex: 'account',
        key: 'account',
        width: '16%',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'account', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                placeholder='账户'
              />
            );
          }
          return text;
        },
      },
      {
        title: '账户名称',
        dataIndex: 'name',
        key: 'name',
        width: '16%',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'name', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                placeholder='账户名称'
              />
            );
          }
          return text;
        },
      },
      {
        title: '开户行',
        dataIndex: 'bank',
        key: 'bank',
        width: '16%',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'bank', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                placeholder='开户行'
              />
            );
          }
          return text;
        },
      },
      {
        title: '机构',
        dataIndex: 'institution',
        key: 'institution',
        width: '12%',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Select style={{ width: '100%' }} onChange={(e) => this.handleInstitutionChange(e, 'institution', record.key)} value={text} placeholder='请选择'>
                {generateSelect('MAAT_PRODUCT_ACCOUNT_INSTITUTION', dictMap)}
              </Select>
            );
          }
          return showValue('MAAT_PRODUCT_ACCOUNT_INSTITUTION', dictMap, text);
        },
      },
      {
        title: '席位',
        dataIndex: 'seat',
        key: 'seat',
        width: '16%',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                disabled={record.institution !== '2' && record.institution !== '3'}
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'seat', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                placeholder='席位'
              />
            );
          }
          return text;
        },
      },
    ];
    const transactionColumns = [
      {
        title: '交易模式',
        dataIndex: 'modes',
        key: 'modes',
        width: '40%',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Select style={{ width: '100%' }} onChange={(e) => this.handleFieldChange(e, 'modes', record.key)} value={text} placeholder='请选择'>
                {generateSelectForObj(TransactionMode)}
              </Select>
            );
          }
          return showValueForObj(TransactionMode, text);
        },
      },
      {
        title: '交易场所',
        dataIndex: 'place',
        key: 'place',
        width: '40%',
        align: 'left',
        render: (text, record) => {
          if (record.editable) {
            text = typeof text == 'string' ? text.split(',') : text;
            return (
              <Select style={{ width: '100%' }} mode='multiple' onChange={(e) => this.handleFieldChange(e, 'place', record.key)} value={text} placeholder='请选择'>
                {generateSelectForObj(AccountConfigAllowedMarket)}
              </Select>
            );
          }
          return showValueForObj(AccountConfigAllowedMarket, text);
        },
      },
    ];
    const fundColumns = [
      {
        title: '期数',
        dataIndex: 'nper',
        key: 'nper',
        width: '20%',
        render: (text, record) => {
          if (record.editable) {
            return (
              <Input
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'nper', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                placeholder='期数'
              />
            );
          }
          return text;
        },
      },
      {
        title: '累计投入金额',
        dataIndex: 'aggregateMoney',
        key: 'aggregateMoney',
        render: (text, record) => {
          if (record.editable) {
            return (
              <InputNumber
                style={{ width: '100%' }}
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'aggregateMoney', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                min={0}
                precision={2}
                max={999999999999}
                formatter={(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                parser={(value) => value.replace(/\$\s?|(,*)/g, '')}
                placeholder='累计投入金额'
              />
            );
          }
          return !text ? '' : `${text}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
        },
      },
      {
        title: '累计份额',
        dataIndex: 'aggregateAmount',
        key: 'aggregateAmount',
        render: (text, record) => {
          if (record.editable) {
            return (
              <InputNumber
                style={{ width: '100%' }}
                value={text}
                autoFocus
                onChange={(e) => this.handleFieldChange(e, 'aggregateAmount', record.key)}
                onKeyPress={(e) => this.handleKeyPress(e, record.key)}
                min={0}
                precision={2}
                max={999999999999}
                formatter={(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                parser={(value) => value.replace(/\$\s?|(,*)/g, '')}
                placeholder='累计投入金额'
              />
            );
          }
          return !text ? '' : `${text}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
        },
      },
    ];
    let columns = [];
    if (type === 'cost') columns = costColumns;
    if (type === 'account') columns = accountColumns;
    if (type === 'fund') columns = fundColumns;
    if (type === 'trusteeship') columns = trusteeshipColumns;
    if (type === 'capital') columns = capitalColumns;
    if (type === 'transaction') columns = transactionColumns;

    if (!editabled) {
      columns.push({
        title: '操作',
        dataIndex: 'id',
        key: 'id',
        render: (text, record) => {
          if (!!record.editable && this.state.loading) {
            return '\\';
          }
          if (record.editable) {
            if (record.isNew) {
              return (
                <span>
                  <a onClick={(e) => this.saveRow(e, record.key)}>添加</a>
                  <Divider type='vertical' />
                  <Popconfirm title='是否要删除此行？' onConfirm={() => this.remove(record.key)}>
                    <a>删除</a>
                  </Popconfirm>
                </span>
              );
            }
            return (
              <span>
                <a onClick={(e) => this.saveRow(e, record.key)}>保存</a>
                <Divider type='vertical' />
                <a onClick={(e) => this.cancel(e, record.key)}>取消</a>
              </span>
            );
          }
          return (
            <span>
              <a onClick={(e) => this.toggleEditable(e, record.key)}>编辑</a>
              <Divider type='vertical' />
              <Popconfirm title='是否要删除此行？' onConfirm={() => this.remove(record.key)}>
                <a>删除</a>
              </Popconfirm>
            </span>
          );
        },
      });
    }
    return columns;
  };
  cancel(e, key) {
    this.clickedCancel = true;
    e.preventDefault();
    const newData = this.state.data.map((item) => ({ ...item }));
    const target = this.getRowByKey(key, newData);
    if (this.cacheOriginData[key]) {
      Object.assign(target, this.cacheOriginData[key]);
      target.editable = false;
      delete this.cacheOriginData[key];
    }
    this.setState({ data: newData });
    this.clickedCancel = false;
  }

  render() {
    const { editabled } = this.props;
    return (
      <>
        {editabled ? '' : <PrimaryC style={{ marginBottom: 16 }} onClick={this.newMember} title='新增'></PrimaryC>}
        <TableC hidePage={true} rowKey={'id'} columns={this.generateColumns()} loading={this.state.loading} dataSource={this.state.data} pagination={false} />
      </>
    );
  }
}
